<template>
  <div class="app-container">

    <!--新增按钮-->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input placeholder="门店名称" v-model="listQuery.shopName" style="width: 200px;" class="filter-item"
                    @keyup.enter.native="handleFilter"/>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline"
                     @click="handleCreate">新增
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!--表格主体-->
    <el-row>
      <el-col :span="24" :gutter="24">
        <el-table
          v-loading="listLoading"
          :data="list"
          :height="tableHeight"
          element-loading-text="Loading"
          border
          fit
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" style="width: 10%">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <el-table-column label="门店号" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.shopId }}
            </template>
          </el-table-column>
          <el-table-column label="门店名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.shopName }}
            </template>
          </el-table-column>
          <el-table-column label="门店省份名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.shopArea }}</span>
            </template>
          </el-table-column>
          <el-table-column label="门店城市名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.shopAreaName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="门店详细地址" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.shopAddress }}</span>
            </template>
          </el-table-column>
          <el-table-column label="门店电话" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.shopTel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="门店介绍" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.shopDesc }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" show-overflow-tooltip style="width: 10%" label="创建时间">
            <template slot-scope="scope">
              <i class="el-icon-time"/>
              <span>{{ scope.row.createdTime | timeFilter}}</span>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="有效标志" style="width: 10%" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.validFlag | statusFilter">{{ scope.row.validFlag | validFilter}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <pagination v-show="total>0" :total="total"
                :page.sync="listQuery.pageNum"
                :limit.sync="listQuery.pageSize"
                layout="total, sizes, prev, pager, next"
                style="float:right;"
                @pagination="fetchData"/>

    <!--编辑弹窗-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm"
               :rules="rules"
               :model="temp"
               label-position="right"
               label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店号" label-width="105px" prop="shopId">
              <el-input v-model="temp.shopId"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店名称" label-width="105px" prop="shopName">
              <el-input v-model="temp.shopName"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="省份选择代码" label-width="105px" prop="shopArea">
              <el-select v-model="temp.shopArea" filterable @change="cityChange" clearable placeholder="请选择有效省份">
              <el-option
                v-for="item in provinceOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省市区名称" label-width="105px" prop="shopAreaName">
              <el-select v-model="temp.shopAreaName" filterable clearable placeholder="请选择有效城市">
                <el-option
                  v-for="item in cityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店详细地址" prop="shopAddress">
              <el-input v-model="temp.shopAddress"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店电话" prop="shopTel">
              <el-input v-model="temp.shopTel"/>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="门店图片" label-width="120px" prop="shopImg">
              <el-upload
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="uploadUrl"
                class="avatar-uploader">
                <img v-if="temp.shopImg" :src="temp.shopImg" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="有效标志">
              <el-switch
                v-model="validSwitch"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="门店介绍" prop="shopDesc">
              <el-input type="textarea" v-model="temp.shopDesc"/>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import SxShopInfoApi from '@/api/manage/SxShopInfoApi';
  import config from '@/assets/js/provincesCity';
  import waves from '@/directive/waves'; // Waves directive
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  const provincesAllArr = config.provincesAll;
  const provincesArr = config.provinces;

  export default {
    directives: {waves},
    components: {Pagination},
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      },
      validFilter(status) {
        const statusMap = {
          1: '有效',
          0: '作废'
        }
        return statusMap[status]
      },
      timeFilter(time) {
        if (time) {
          return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
        } else {
          return ''
        }
      }
    },
    data() {
      return {
        shopName: 0,
        list: null,
        listLoading: true, //表格加载框
        total: 1, //分页总数
        uploadUrl: process.env.BASE_API + '/file/upload',
        tableHeight: window.innerHeight - 220, //表格高度
        provincesAllArr: provincesAllArr,//所有省份市的数据
        provincesArr: provincesArr,//所有省份的数据
        provinceOptions: [], //省份下拉框选择项
        cityOptions: [],//城市下拉框选择项
        listQuery: {
          pageNum: 1,
          pageSize: 10,
          query: '',
          shopId: '',
          validFlag: undefined,
          shopName: ''
        },
        importanceOptions: [1, 2, 3],
        sortOptions: [{label: 'ID Ascending', key: '+id'}, {label: 'ID Descending', key: '-id'}],
        statusOptions: {
          1: '超级管理员',
          0: '普通用户'
        },
        showReviewer: false,
        temp: {},
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },

        dialogPvVisible: false,
        pvData: [],
        rules: {
          shopId: [{required: true, message: '门店ID不能为空', trigger: 'change'}],
          shopName: [{required: true, message: '门店名称不能为空', trigger: 'change'}]
        },
        downloadLoading: false
      }
    },
    computed: {
      validSwitch: {
        // getter
        get: function () {
          return this.temp.validFlag === '1'
        },
        // setter
        set: function (newValue) {
          if (newValue) {
            this.temp.validFlag = '1'
          } else {
            this.temp.validFlag = '0'
          }
        }
      }
    },
    created() {
      this.fetchData()
    },
    mounted() {
      this.initProvinces();

    },
    methods: {

      handleAvatarSuccess(res, file) {
        this.temp.shopImg = res.data[0]
      },

      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 50
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 50MB!')
        }
        return isLt2M
      },

      cityChange(rowdata) {

        let _sel = this;
        let tempArr = [];
        this.$_.forEach(this.provincesAllArr,function (b, a) {
          if (b.provinceName == rowdata) {
            tempArr = b.citys;
          }
        });

        const tempArr1 = this.$_.map(tempArr, function(n) {
          return {label: n.citysName, value: n.citysName};
        });

        _sel.cityOptions = tempArr1;
      },

      initProvinces() {

        const tempArr = this.$_.map(this.provincesArr, function(n) {
          return {label: n.provinceName, value: n.provinceName};
        });
        this.provinceOptions = tempArr;

      },
      fetchData() {
        let that = this;
        this.listLoading = true
        this.$http.all([SxShopInfoApi.getPage(this.listQuery)])
          .then(this.$http.spread(function (perms) {
            that.list = perms.rows
            that.total = perms.total
            that.listLoading = false
          }));
      },
      /**
       * 新增弹窗
       */
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 清空弹窗内容
       */
      resetTemp() {
        this.temp = {
          shopName: '',
          shopTel: '',
          shopArea: '',
          shopAreaName: '',
          shopAddress: '',
          shopDesc: '',
          shopImg: '',
          validFlag: '1'
        }
        this.cityOptions = [];
      },
      /**
       * 确定新增
       */
      createData() {
        let that  = this;
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            SxShopInfoApi.insert(this.temp).then(() => {

              // this.list.unshift(this.temp);
              this.dialogFormVisible = false;
              this.fetchData();
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData();
                }
              })
            }).catch(function(data) {
              that.dialogFormVisible = false;
              that.$message({
                title: '失败',
                message: data.error,
                type: 'warning',
                duration: 1000,
                onClose() {
                  that.fetchData();
                }
              })
            });
          }
        })
      },
      /**
       * 编辑弹窗
       */
      handleUpdate(row) {

        this.temp = Object.assign({}, row)
        this.cityChange(this.temp.shopArea);
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 确认编辑
       */
      updateData() {
        let that  = this;
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            SxShopInfoApi.update(tempData).then(() => {
              for (const v of this.list) {
                if (v.empId === this.temp.empId) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData();
                }
              })
            })
          }
        })
      },
      /**
       * 删除操作
       */
      handleDelete(row) {
        SxShopInfoApi.remove({shopId: row.shopId}).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      /**
       * 搜索过滤
       */
      handleFilter() {
        this.listQuery.page = 1
        this.fetchData()
      },
    }
  }
</script>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 600px;
    height: 300px;
    display: block;
  }

</style>
